package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author:YZN
 * @date:2022/12/30
 * @description:
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String PATH;

    @Autowired
    private HttpServletResponse response;
    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-","") + suffix;

        try {
            file.transferTo(new File(PATH + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }

    /**
     * 下载回显图片
     */
    @GetMapping("/download")
    public void download(@RequestParam("name") String name) throws IOException{
        //todo 1.找到本地图片
        File file = new File(PATH+name);
        //todo 2.读取输入流
        FileInputStream fis = new FileInputStream(file);
        //todo 3.通过网络流给前端
        ServletOutputStream os = response.getOutputStream();
        //todo 4.边读本地资源边通过网络流写给前端
        int len = 0;
        byte[] bytes = new byte[2048];
        while ((len = fis.read(bytes)) != -1) {
            os.write(bytes,0,len);
            os.flush();
        }
        //todo 5.关流
        os.close();
        fis.close();

    }
}
